package com.vcc.boss.controller;


import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.idev.excel.ExcelWriter;
import cn.idev.excel.write.metadata.WriteSheet;
import com.mybatisflex.core.paginate.Page;
import com.vcc.core.annotations.RestPack;
import com.vcc.core.derive.admin.DeriveTransaction;
import com.vcc.core.exception.ProgramException;
import com.vcc.core.util.ExportUtil;
import com.vcc.core.util.RegexUtil;
import com.vcc.data.entity.Transaction;
import com.vcc.service.boss.response.trans.TransactionVoBoss;
import com.vcc.service.sa.BossUserUtil;
import com.vcc.service.service.ClearTranService;
import com.vcc.service.service.TransactionService;
import com.vcc.service.service.UserCardService;
import com.vcc.service.service.UserService;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@Log4j2
@RestController
@RequestMapping("trans")
public class TransController {

    @Autowired
    private UserCardService userCardService;
    @Autowired
    private UserService userService;
    @Autowired
    private TransactionService transactionService;
    @Autowired
    private ClearTranService clearTranService;


    @RestPack
    @SaCheckLogin
    @SaCheckPermission(value = "card:transaction:list:view")
    @GetMapping("authPaging")
    public Page<TransactionVoBoss> authPaging(
            Page<Transaction> pageable,
            Long targetUserId,
            String cardNumber,
            Long userCardId,
            String startDate,
            String endDate,
            String type,
            String status,
            Long cardTypeId,
            String channelCode
    ) {
        Page<Transaction> paging = transactionService.paging(BossUserUtil.getId(), pageable, targetUserId, status, type, cardNumber, startDate, endDate, userCardId,cardTypeId,channelCode);
        if (paging.getRecords().isEmpty()) {
            return Page.of(
                    paging.getPageNumber(),
                    paging.getPageSize()
            );
        }
        return paging.map(TransactionVoBoss::new);

    }

    @RestPack
    @SaCheckPermission(value = "card:transaction:list:derive")
    @SaCheckLogin
    @GetMapping("deriveAuthData")
    public void deriveAuthData(
            Long targetUserId,
            String cardNumber,
            String startDate,
            String endDate,
            String type,
            Long userCardId,
            String status,
            Long cardTypeId,
            String channelCode,
            HttpServletResponse response
    ) {
        if (RegexUtil.checkStringIsNull(startDate)) {
            throw new ProgramException("请选择开始时间");
        }
        if (RegexUtil.checkStringIsNull(endDate)) {
            throw new ProgramException("请选择结束时间");
        }
        Long pages = 1L;
        Page<Transaction> paging;
        String fileName = System.currentTimeMillis() + "交易记录.xlsx";
        ExcelWriter excelWriter;
        try {
            ExportUtil.setExcelResponseHeaders(response, fileName);
            excelWriter = ExportUtil.createExcelWriter(response.getOutputStream(), DeriveTransaction.class);
        } catch (Exception e) {
            log.error("导出交易记录数据失败", e);
            throw new ProgramException("导出交易记录数据失败");
        }
        WriteSheet writeSheet = ExportUtil.createWriteSheet("交易记录", DeriveTransaction.class);
        do {
            paging = transactionService.paging(BossUserUtil.getId(), Page.of(pages++, 500), targetUserId, status, type, cardNumber, startDate, endDate, userCardId,cardTypeId,channelCode);
            List<DeriveTransaction> list = paging.getRecords().stream().map(it -> {
                return DeriveTransaction.builder()
                        .id(it.getId())
                        .tranId(it.getTranId())
                        .originalTranId(it.getOriginalTranId())
                        .channelTranId(it.getChannelTranId())
                        .channelOriginalTranId(it.getOriginalChannelTranId())
                        .account(it.getAccount())
                        .cardNumber(it.getCardNumber())
                        .userCardId(it.getUserCardId())
                        .merchantName(it.getMerchantName())
                        .tranDate(it.getTranDate())
                        .settleDate(it.getSettleDate())
                        .billingAmount(it.getBillingAmount())
                        .billingCurrency(it.getBillingCurrency())
                        .merchantAmount(it.getMerchantAmount())
                        .merchantCurrency(it.getMerchantCurrency())
                        .authType(it.getTransactionType())
                        .status(it.getStatus())
                        .remark(it.getRemark())
                        .dealerAccount(it.getDealerAccount())
                        .build();
            }).toList();
            ExportUtil.writeData(excelWriter, writeSheet, list);
            list = null;
        } while (!(pages).equals(paging.getTotalPage() + 1));
        ExportUtil.closeExcelWriter(excelWriter);
    }

//
//    @RestPack
//    @SaCheckPermission(value = {"boss-clear"})
//    @GetMapping("clearPaging")
//    public Page<ClearTranVo> clearPaging(
//            @CurrentUserId Long userId,
//            @CurrentClientIp String clientIp,
//            Page<ClearTran> pageable,
//            Long targetUserId,
//            String cardNumber,
//            String startDate,
//            String endDate,
//            String type
//    ) {
//        Page<ClearTran> paging = clearTranService.paging(userId, pageable, targetUserId, type, cardNumber, startDate, endDate);
//        return paging.map(it -> {
//            String account = userService.getAccountById(it.getUserId());
//            return new ClearTranVo(it, account);
//        });
//    }
//
//    @RestPack
//    @SaCheckPermission(value = {"boss-clear"})
//    @GetMapping("deriveClearData")
//    public void deriveClearData(
//            @CurrentUserId Long userId,
//
//            @CurrentClientIp String clientIp,
//            Long targetUserId,
//            String cardNumber,
//            String startDate,
//            String endDate,
//            String type,
//            HttpServletResponse response
//    ) {
//        Long pages = 1L;
//        Page<ClearTran> pageable;
//        Page<ClearTran> paging;
//        SXSSFWorkbook sxssfWorkbook = FileUtil.createClearTitle(10000);
//        do {
//            pageable = new Page<>(pages++, 20);
//            paging = clearTranService.paging(userId, pageable, targetUserId, type, cardNumber, startDate, endDate);
//            List<ClearTranFilPojo> list = paging.getRecords().stream().map(it -> {
//                String account = userService.getAccountById(it.getUserId());
//                return new ClearTranFilPojo(
//                        it.getTransactionId(),
//                        account,
//                        it.getCardNumber(),
//                        it.getCardId(),
//                        it.getMerchantName(),
//                        DateUtil.format("yyyy-MM-dd", it.getTranDate()),
//                        DateUtil.format("yyyy-MM-dd", it.getPostingDate()),
//                        it.getBillingAmount(),
//                        it.getBillingCurrency(),
//                        it.getMerchantAmount(),
//                        it.getMerchantCurrency(),
//                        it.getType(),
//                        it.getRemark()
//                );
//            }).collect(Collectors.toList());
//            FileUtil.deriveClearData(sxssfWorkbook, list, paging.getPageNumber(), paging.getPageSize());
//        } while (!(pages).equals(paging.getTotalPage() + 1));
//        String fileName = System.currentTimeMillis() + "清算交易明细.xlsx";
//        FileUtil.downXlsxFile(response, sxssfWorkbook, fileName);
//    }
}
